package tpase.KeyServer.Service.Impl;

import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.jpbc.Field;
import it.unisa.dia.gas.jpbc.Pairing;
import tpase.KeyServer.DAO.KeyShareDao;
import tpase.KeyServer.DAO.UserAuthDao;
import tpase.KeyServer.DO.KeyShare;
import tpase.KeyServer.Service.KeyServerSetupService;
import tpase.KeyServer.VO.PublicParam;
import tpase.KeyServer.VO.SecretKey;
import tpase.util.Util;

import java.util.Map;

public class KeyServerSetupServiceImpl implements KeyServerSetupService {
    private String serverId;
    private KeyShareDao keyShareDao;
    private UserAuthDao userAuthDao;

    public KeyServerSetupServiceImpl(String serverId) {
        this.serverId = serverId;
        String configPath = "config/server" + serverId + "/config.properties";
        keyShareDao = new KeyShareDao(configPath);
        userAuthDao = new UserAuthDao(configPath);
    }
    @Override
    public void storeSi(String jpbcPath, String publicParamPath, Map<String, byte[]> map) {
        byte[] idxBytes = map.get("idx");
        int idx = (int) idxBytes[0];
        Pairing pairing = Util.getPairing(jpbcPath);
        Field Zr = pairing.getZr();
        Element x = Zr.newElementFromBytes(map.get("x"));
        Element s_i = Zr.newElementFromBytes(map.get("s" + idx));
        map.remove("idx");
        map.remove("x");
        map.remove("s" + idx);
        PublicParam publicParam = new PublicParam();
        publicParam.setMap(map);
        SecretKey secretKey = new SecretKey(idx, x.toBytes(), s_i.toBytes());

        Util.writeJson(publicParamPath, publicParam);

        KeyShare keyShare = new KeyShare(pairing.getZr().newElementFromBytes(secretKey.getX()).toString(), secretKey.getS_i());
        keyShareDao.clearKeyShare();
        keyShareDao.storeKeyShare(keyShare);
    }

    @Override
    public void clear() {
        keyShareDao.clearKeyShare();
        userAuthDao.clearUserAuth();
    }
}
